/*
 * Galaxium Messenger
 * Copyright (C) 2005-2007 Ben Motmans <ben.motmans@gmail.com>
 * Copyright (C) 2005-2007 Philippe Durand <draekz@gmail.com>
 *
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.Text;
using System.Security.Cryptography;

namespace Galaxium.Protocol.Msn
{
	internal sealed class Challenge : AbstractChallenge
	{
		private string _productID;
		private string _productKey;
		
		public string ProductID
		{
			get { return _productID; }
		}
		
		public string ProductKey
		{
			get { return _productKey; }
		}

		public Challenge (string productID, string productKey)
		{
			_productID = productID;
			_productKey = productKey;
		}

		public override string GetChallengeResponse (string challenge)
		{
			string hash = CreateMD5HexString (challenge + _productKey);
			int[] smallChunks = CreateSmallChunks (hash);
			string chal = challenge + _productID;
			chal = chal.PadRight (chal.Length + (8 - chal.Length % 8), '0');
			int[] bigChunks = CreateBigChunks (chal);
			long key = CalculateKey (bigChunks, smallChunks);

			return (String.Format ("{0:x}", Convert.ToInt64 (hash.Substring (0, 16), 16) ^ key).PadLeft (16, '0') +
					String.Format ("{0:x}", Convert.ToInt64 (hash.Substring (16, 16), 16) ^ key).PadLeft (16, '0'));
		}
	}
}